import _ from "lodash";
import $cmpnt, { IBindDbField, ICmpnt } from "xcore/cmpnt";
import { AttrHandler, IPropertyItem } from "../../types";
import $data, { EnumItem, enums } from "xcore/data";

export const getSwitchCmpnt: AttrHandler = (pis: IPropertyItem[], cmpnt: ICmpnt) => {

    // 查找是否存在
    let switchCmpnt: IPropertyItem = { icon: "fa fa-stumbleupon", label: "切换组件", children: [] }
    let exists = pis.some(item => item.label === switchCmpnt.label);
    if (exists || !cmpnt.props.dbField) return;

    // 创建绑定组件
    let dbField: IBindDbField = cmpnt.props.dbField;

    // 构建组件实例
    switchCmpnt.children = []
    $data.provider.meta.getMetaColumn(dbField.fieldId).then((field: any) => {
        if (!field) return;
        const cmpntType = enums.joinType("cmpnt", enums.getValueChar(field.type));
        let cmpntItems: EnumItem[] = enums.getItems(cmpntType, field.source)
        for (let iCmpnt of cmpntItems) {
            const optCmpnt = $cmpnt.find("switch").clone();
            // 创建新组件实例
            let newCmpnt = $cmpnt.find(iCmpnt.value as string).clone();
            newCmpnt.valueKey = field.name;
            newCmpnt.props.placeholder = cmpnt.props.placeholder;
            // if (newCmpnt.ctl.name == "Switch") {
            //     newCmpnt.props["active-value"] = 1
            //     newCmpnt.props["inactive-value"] = 0
            // }
            let nameKey = `${field.name}_${optCmpnt.id}`
            optCmpnt.valueKey = nameKey;

            let item: IPropertyItem = {
                icon: newCmpnt.ctl.icon,
                label: newCmpnt.ctl.text,
                data: {}, events: {}
            }
            item.events = {
                click: () => {
                    $data.func.replace(cmpnt, newCmpnt);
                }
            }
            switchCmpnt.children?.push(item);
        }
        pis.push(switchCmpnt);
    });
}